<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

	public function Main(){
		parent::__construct();
		parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
		$CI = & get_instance();
		$CI->config->load("facebook",TRUE);
		$config = $CI->config->item('facebook');
		$this->load->library('Facebook', $config);
	}

	function index(){
		
		$args = array('scope'=>'email,user_birthday');
		// Try to get the user's id on Facebook
		$user = $this->facebook->getUser();
		$facebookFlag = false;

        if ($user) {
        	
            try {
            	
                $facebookuser = $this->facebook->api('/me');
                $facebookFlag = true;
                $username = $facebookuser['email'];
                
                if (!$this->ion_auth->username_check($username))
                {
                	
                	$username = $facebookuser['email'];
                	$password = 'temp123';
                	$firstname = $facebookuser['first_name'];
                	$lastname = $facebookuser['last_name'];
                	$email = $username;
                	$additional_data = array(
                			'first_name' => $firstname,
                			'last_name' => $lastname,
                	);
                	
                	$group_name = 'members';
                	$this->ion_auth->register($username, $password, $email, $additional_data, $group_name);
                	$ionuser = $this->ion_auth->get_user_by_username($username);
                	$this->ion_auth->activate($ionuser->id);
                	$session = $this->facebook->destroySession();
                	$identity = $ionuser->username;
                	$remember = TRUE; // remember the user
                	$loggedIn = $this->ion_auth->loginNoPassword($identity, $remember);
                	
                	$user = $this->ion_auth->get_user();
                	
                } else {
                	
                	$ionuser = $this->ion_auth->get_user_by_username($username);
                	
                	$identity = $ionuser->username;
                	$remember = TRUE; // remember the user
                	$loggedIn = $this->ion_auth->loginNoPassword($identity, $remember);
                	
                	$session = $this->facebook->destroySession();
                	
                	$user = $this->ion_auth->get_user();
                }
                
            } catch (FacebookApiException $e) {
                $user = null;
            }
        }
        
        if($user){
        	$user = $this->ion_auth->get_user();
        	$groups = $this->ion_auth->get_groups();
        }
        
        if ($user) {
        	$data['user_profile']= $user;
            $data['logout_url'] = $this->facebook->getLogoutUrl();
        } else {
            $data['login_url'] = $this->facebook->getLoginUrl($args);
        }
        
        $this->load->view('main_index',$data);
	}

}

?>